package com.pet.web.controller.wechat;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.pet.common.core.controller.BaseController;
import com.pet.common.core.domain.AjaxResult;
import com.pet.common.core.domain.entity.SysUser;
import com.pet.common.core.page.TableDataInfo;
import com.pet.framework.exception.BadTokenException;
import com.pet.framework.wechat.WechatService;
import com.pet.system.domain.PetCart;
import com.pet.system.domain.PetProduct;
import com.pet.web.controller.system.vo.CustomerBody;
import com.pet.web.controller.wechat.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 微信登录验证
 *
 * @author pet
 */
@Api(value = "微信接口", tags = "微信小程序的接口管理")
@RestController
@RequestMapping("/wechat")
public class WechatController extends BaseController {
    @Autowired
    private WechatService wechatService;

    /**
     * 登录方法
     *
     * @param wxLoginBody 登录信息
     * @return 结果
     */
    @ApiOperation("登录")
    @ApiImplicitParam(name = "wxLoginBody", value = "wxLoginBody", required = true, dataTypeClass = WxLoginBody.class)
    @PostMapping("/login")
    public AjaxResult login(@RequestBody WxLoginBody wxLoginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        JSONObject login = wechatService.login(wxLoginBody.getJs_code());
        ajax.put("loginResult", login);
        return StringUtils.isNotBlank(login.getString("openid")) ? ajax : AjaxResult.error(login.getString("errmsg"));
    }

    /**
     * 登录之后，补充客户信息
     *
     * @param customerBody 客户信息
     * @return 结果
     */
    @ApiOperation("登录之后，补充客户信息")
    @ApiImplicitParam(name = "customerBody", value = "customerBody", dataTypeClass = CustomerBody.class)
    @PostMapping("/updateCustomer")
    public AjaxResult updateCustomer(@RequestBody CustomerBody customerBody) {
        // 生成令牌
        String nickName = customerBody.getNickName();
        if (StringUtils.isBlank(nickName)) {
            nickName = "微信用户";
        }
        int update = wechatService.updateCustomer(customerBody.getOpenid(), nickName);
        return toAjax(update);
    }

    /**
     * 获取手机号码
     *
     * @param wxPhoneBody code
     * @return 结果
     */
    @ApiOperation("获取手机号")
    @ApiImplicitParam(name = "wxPhoneBody", value = "wxPhoneBody", required = true, dataTypeClass = WxPhoneBody.class)
    @PostMapping("/getMobile")
    public AjaxResult getMobile(@RequestBody WxPhoneBody wxPhoneBody) {
        AjaxResult ajax = AjaxResult.success();
        String phoneNum = wechatService.getMobile(wxPhoneBody.getOpenid(), wxPhoneBody.getCode());
        ajax.put("phoneNum", phoneNum);
        return StringUtils.isBlank(phoneNum) ? AjaxResult.error() : ajax;
    }

    /**
     * 获取商户列表
     *
     * @param wxBody 参数openid
     * @return 结果
     */
    @ApiOperation("获取商户列表")
    @ApiImplicitParam(name = "wxBody", value = "wxBody", required = true, dataTypeClass = WxBody.class)
    @PostMapping("/getMerchantList")
    public AjaxResult getMerchantList(@RequestBody WxBody wxBody, HttpServletResponse response) throws IOException {
        try {
            AjaxResult ajax = AjaxResult.success();
            List<SysUser> userList = wechatService.getMerchantList(wxBody.getOpenid());
            ajax.put("merchantList", userList);
            return ajax;
        } catch (BadTokenException e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(new JSONObject().fluentPut("msg", "token过期").toJSONString());
            return null;
        }
    }

    /**
     * 加入商家
     *
     * @param wxMerchantBody 参数openid,商家码
     * @return 结果
     */
    @ApiOperation("加入商家")
    @ApiImplicitParam(name = "wxMerchantBody", value = "wxMerchantBody", required = true, dataTypeClass = WxMerchantBody.class)
    @PostMapping("/addMerchant")
    public AjaxResult addMerchant(@RequestBody WxMerchantBody wxMerchantBody, HttpServletResponse response) throws IOException {
        try {
            JSONObject result = wechatService.addMerchant(wxMerchantBody.getOpenid(), wxMerchantBody.getMerchantCode());
            return Integer.valueOf(0).equals(result.getInteger("errcode")) ? AjaxResult.success() : AjaxResult.error(result.getString("errmsg"));
        } catch (BadTokenException e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(new JSONObject().fluentPut("msg", "token过期").toJSONString());
            return null;
        }
    }

    /**
     * 获取类目列表
     *
     * @param wxBody 参数userId
     * @return 结果
     */
    @ApiOperation("获取类目列表")
    @ApiImplicitParam(name = "wxBody", value = "wxBody", required = true, dataTypeClass = WxBody.class)
    @PostMapping("/getCategoryList")
    public AjaxResult getCategoryList(@RequestBody WxBody wxBody, HttpServletResponse response) throws IOException {
        try {
            AjaxResult ajax = AjaxResult.success();
            List<String> categoryList = wechatService.getCategoryList(wxBody.getOpenid());
            ajax.put("categoryList", categoryList);
            return ajax;
        } catch (BadTokenException e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(new JSONObject().fluentPut("msg", "token过期").toJSONString());
            return null;
        }
    }

    /**
     * 获取品牌列表
     *
     * @param wxBrandListBody 参数userId
     * @return 结果
     */
    @ApiOperation("获取品牌列表")
    @ApiImplicitParam(name = "wxBrandListBody", value = "wxBrandListBody", dataTypeClass = WxBrandListBody.class)
    @PostMapping("/getBrandList")
    public AjaxResult getBrandList(@RequestBody WxBrandListBody wxBrandListBody, HttpServletResponse response) throws IOException {
        try {
            List<String> brandList = wechatService.getBrandList(wxBrandListBody.getOpenid(), wxBrandListBody.getUserId(),
                    wxBrandListBody.getCategory());
            return AjaxResult.success().put("brandList", brandList);
        } catch (BadTokenException e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(new JSONObject().fluentPut("msg", "token过期").toJSONString());
            return null;
        }
    }

    /**
     * 获取产品列表
     *
     * @param wxBrandBody 参数brandId
     * @return 结果
     */
    @ApiOperation("获取产品列表")
    @ApiImplicitParam(name = "wxBrandBody", value = "wxBrandBody", dataTypeClass = WxBrandBody.class)
    @PostMapping("/getProductList")
    public AjaxResult getMerchantList(@RequestBody WxBrandBody wxBrandBody, HttpServletResponse response) throws IOException {
        try {
            AjaxResult ajax = AjaxResult.success();
            List<PetProduct> productList = wechatService.getProductList(wxBrandBody.getOpenid(),
                    wxBrandBody.getBrandName(), wxBrandBody.getCategory(), wxBrandBody.getUserId());
            ajax.put("productList", productList);
            return ajax;
        } catch (BadTokenException e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(new JSONObject().fluentPut("msg", "token过期").toJSONString());
            return null;
        }
    }

    /**
     * 商户申请
     *
     * @param wxApplyBody 参数
     * @return 结果
     */
    @ApiOperation("商户申请")
    @ApiImplicitParam(name = "wxApplyBody", value = "入参", dataTypeClass = WxApplyBody.class)
    @PostMapping("/merchantApply")
    public AjaxResult merchantApply(@RequestBody WxApplyBody wxApplyBody, HttpServletResponse response) throws IOException {
        try {
            String msg = wechatService.merchantApply(wxApplyBody.getOpenid(), wxApplyBody.getUserName(), wxApplyBody.getMobile());
            return null == msg ? AjaxResult.success() : AjaxResult.error(msg);
        } catch (BadTokenException e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(new JSONObject().fluentPut("msg", "token过期").toJSONString());
            return null;
        }
    }

    /**
     * 查询采购单列表
     *
     * @param wxCartSelectBody 参数
     * @return 结果
     */
    @ApiOperation("查询采购单列表")
    @ApiImplicitParam(name = "wxCartSelectBody", value = "wxCartSelectBody", dataTypeClass = WxCartSelectBody.class)
    @PostMapping("/getCartList")
    public TableDataInfo list(@RequestBody WxCartSelectBody wxCartSelectBody, HttpServletResponse response) throws IOException {
        try {
            startPage();
            JSONArray list = wechatService.selectPetCartListWx(wxCartSelectBody.getOpenid(), wxCartSelectBody.getUserId());
            return getDataTable(list);
        } catch (BadTokenException e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(new JSONObject().fluentPut("msg", "token过期").toJSONString());
            return null;
        }
    }

    /**
     * 添加到采购单
     *
     * @param wxCartBody 参数
     * @return 结果
     */
    @ApiOperation("添加到采购单")
    @ApiImplicitParam(name = "wxCartBody", value = "wxCartBody", dataTypeClass = WxCartBody.class)
    @PostMapping("/addCart")
    public AjaxResult add(@RequestBody WxCartBody wxCartBody, HttpServletResponse response) throws IOException {
        try {
            PetCart petCart = new PetCart();
            petCart.setOpenid(wxCartBody.getOpenid());
            petCart.setProductId(wxCartBody.getProductId());
            return toAjax(wechatService.insertPetCart(petCart));
        } catch (BadTokenException e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(new JSONObject().fluentPut("msg", "token过期").toJSONString());
            return null;
        }
    }

    /**
     * 删除出采购单
     *
     * @param id 参数
     * @return 结果
     */
    @ApiOperation("删除出采购单")
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        return toAjax(wechatService.deletePetCartById(id));
    }

    /**
     * 生成采购单记录
     *
     * @param wxOrderBody 参数
     * @return 结果
     */
    @ApiOperation(value = "生成采购单记录")
    @ApiImplicitParam(name = "wxOrderBody", value = "wxOrderBody", dataTypeClass = WxOrderBody.class)
    @PostMapping("/addOrder")
    public AjaxResult add(@RequestBody WxOrderBody wxOrderBody) {
        String cartIds = wxOrderBody.getCartIdList().stream().map(String::valueOf).collect(Collectors.joining(","));
        return toAjax(wechatService.insertPetOrders(wxOrderBody.getOpenid(), cartIds));
    }

    @ApiOperation(value = "下载商品图片")
    @GetMapping("/downloadImage/{id}")
    public AjaxResult downloadImage(@PathVariable("id") Long id, HttpServletResponse response) {
        PetProduct petProduct = wechatService.selectPetProductImageById(id);
        Object imageUrl=petProduct.getImageUrl();
        if (null ==imageUrl) {
            return AjaxResult.success("产品暂无图片");
        }
        return AjaxResult.success(imageUrl);
    }
}
